//
//  HPQualityConfirmViewController.m
//  HPZZTong
//
//  Created by Handpay on 14-3-28.
//  Copyright (c) 2014年 Handpay. All rights reserved.
//

#import "HPQualityConfirmViewController.h"
#import "HPConditionTextField.h"
#import "DefineUtil.h"
#import "ZZTongUtility.h"
#import "ZZTongPhotoButton.h"
#import "CSNValidator.h"

@interface HPQualityConfirmViewController (){
    BOOL confirmFlag;  // YES-确认提交界面
    NSInteger currentPhoto;  // 当前上传照片的标志
}
@property (retain, nonatomic) IBOutlet UILabel *cardTitleLabel;
@property(nonatomic, retain)NSArray* personDesArray;
@property(nonatomic, retain)NSArray* cardDesArray;
@property(nonatomic, retain)NSArray* confirmValueArray;

@end

@implementation HPQualityConfirmViewController


#define kPhotoCertFront  0
#define kPhotoCertBack   1
#define kPhotoHead       2
#define kPhotoPlace      3
#define kPhotoLicense    4

#define kPhotoKey       @"photoKey"

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.personDesArray = @[@"姓名",
                                @"身份证号码",
                                @"店铺名称",];
        
        
        currentPhoto = -1;
    }
    return self;
}

- (void)viewDidLoad
{
    confirmFlag = NO;
    NSString* flag = [self.screenData objectForKey:@"confirmFlag"];
    if (flag) {
        if ([flag isEqualToString:@"1"]) {
            confirmFlag = YES;
        }
    }
    NSArray* valueArray = nil;
    NSMutableArray* mutArray = nil;
    NSMutableArray* desArray = [NSMutableArray arrayWithObject:@"收款行"];
    
    
    if (confirmFlag) {
        self.title = @"确认资质材料信息";
        
        NSDictionary* personDic = [self.screenData objectForKey:@"person"];
        
        valueArray = @[[personDic objectForKey:@"name"],
                       [personDic objectForKey:@"certNo"],
                       [personDic objectForKey:@"shopName"],
                       [personDic objectForKey:@"bankName"]];
        
        mutArray = [NSMutableArray arrayWithArray:valueArray];
        NSString* subBankName = [personDic objectForKey:@"subBankName"];
        NSDictionary* provinceInfo = [personDic objectForKey:@"provinceInfo"];
        NSString* provinceName = nil;
        if (provinceInfo) {
            provinceName = [provinceInfo objectForKey:@"provinceName"];
        }
        NSString* areaName = [personDic objectForKey:@"areaName"];
        
        if (![NSString isNilOrEmpty:provinceName]) {
            [mutArray addObject:provinceName];
            [desArray addObject:@"开户省份"];
        }
        if (![NSString isNilOrEmpty:areaName]) {
            [mutArray addObject:areaName];
            [desArray addObject:@"开户地市"];
        }
        if (![NSString isNilOrEmpty:subBankName]) {
            [mutArray addObject:subBankName];
            [desArray addObject:@"开户行"];
        }
        [mutArray addObject:[personDic objectForKey:@"cardNo"]];
        
        [self.nextButton setTitle:@"确认提交" forState:UIControlStateNormal];
        
    }else{
        AccountInfoData* info = ZZT_CLIENG.accountInfo;
        valueArray = @[info.name, info.certNo, info.shopName, info.bankName];
        mutArray = [NSMutableArray arrayWithArray:valueArray];
        if (![NSString isNilOrEmpty:info.provinceName]) {
            [mutArray addObject:info.provinceName];
            [desArray addObject:@"开户省份"];
        }
        if (![NSString isNilOrEmpty:info.areaName]) {
            [mutArray addObject:info.areaName];
            [desArray addObject:@"开户地市"];
        }
        if (![NSString isNilOrEmpty:info.branchBankName]) {
            [mutArray addObject:info.branchBankName];
            [desArray addObject:@"开户行"];
        }
        [mutArray addObject:info.cardNo];
        
        self.title = @"资质信息";
        self.nextButton.hidden = YES;
        self.dateTableView.dataSource = self;
        self.dateTableView.delegate = self;
        self.dateTableView.hidden = NO;
    }
    [desArray addObject:@"银行卡号"];
    self.cardDesArray = desArray;
    self.confirmValueArray = mutArray;
    
    [super viewDidLoad];
    
    [self.navigationController setNavigationBarHidden:NO];
    
    self.personTableView.dataSource = self;
    self.cardTableView.dataSource = self;
    self.personTableView.delegate = self;
    self.cardTableView.delegate = self;
    
    [self.nextButton setBackgroundImage:[[UIImage imageNamed:@"bluebutton.png"] stretchableImageWithLeftCapWidth:9 topCapHeight:0] forState:UIControlStateNormal];
    
    [self.nextButton setBackgroundImage:[[UIImage imageNamed:@"bluebuttonhover.png"] stretchableImageWithLeftCapWidth:9 topCapHeight:0] forState:UIControlStateHighlighted];
    
    CGRect contentFrame = self.contentView.frame;
  
    if (!self.dateTableView.hidden) {
        contentFrame.origin.y = self.dateTableView.frame.origin.y + self.dateTableView.frame.size.height;
    }
    
    self.contentView.frame = contentFrame;
    
    self.scrollView.contentSize = CGSizeMake(ScreenWidth, contentFrame.origin.y + contentFrame.size.height);
    
    self.tabBarController.tabBar.hidden = YES;
    
//    tipsLabel.textColor = kTitleFontColor;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}

- (void)dealloc {
    self.personDesArray = nil;
    self.cardDesArray = nil;
    self.confirmValueArray = nil;
    
    [_personTableView release];
    [_cardTableView release];
    [_nextButton release];
    [_contentView release];
    [_scrollView release];
    [_dateTableView release];
    [_cardTitleLabel release];
//    [tipsLabel release];
    [super dealloc];
}

- (void)viewDidUnload {
    [self setPersonTableView:nil];
    [self setCardTableView:nil];
    [self setNextButton:nil];
    [self setContentView:nil];
    [self setScrollView:nil];
    [self setDateTableView:nil];
    [self setCardTitleLabel:nil];
    [super viewDidUnload];
}
- (NSUInteger)heightWithLabel:(UILabel*)label{
    label.numberOfLines = 0;
    
    CGRect frame = label.frame;
    frame.size.height = 1000;
    label.frame = frame;
    
    [label sizeToFit];
    
    NSUInteger h = label.frame.size.height;
    
    if (h >= 44) {
        h += 5;
    }else{
        h = 44;
    }
    frame.size.height = h;
    label.frame = frame;
    
    return h;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if ([tableView isEqual:self.dateTableView]) {
        return 1;
    }else if ([tableView isEqual:self.cardTableView]){
        return self.cardDesArray.count;
    }
    return 3;
}

- (UITableViewCell *)initPersonTableViewCell:(NSInteger)index{
    UITableViewCell* cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    
    NSString* desStr = [self.personDesArray objectAtIndex:index];
    
    UILabel* desLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, 100, 44)];
    desLabel.textColor = kNormalFontColor;
    desLabel.font = kNormalFont;
    desLabel.text = desStr;
    [cell addSubview:desLabel];
    
    UILabel* textLabel = [[UILabel alloc] initWithFrame:CGRectMake(110, 0, 200, 44)];
    textLabel.textColor = [UIColor blackColor];
    textLabel.font = kNormalFont;
    textLabel.textAlignment = NSTextAlignmentLeft;
    if (ZZT_CLIENG.accountInfo.accountStatus == AccountStatusSuccess && (index == 1)) {
        NSString* veriStr = [self.confirmValueArray objectAtIndex:index];
        NSInteger cardLength = [veriStr length];
        
        NSString* str = [NSString stringWithFormat:@"%@*********%@",[veriStr substringToIndex:3],[veriStr substringFromIndex:(cardLength - 4)]];
        
        textLabel.text = str;
    }else{
        textLabel.text = [self.confirmValueArray objectAtIndex:index];
        
    }
    NSUInteger h = [self heightWithLabel:textLabel];
    if (h > 44) {
        CGRect frame = desLabel.frame;
        frame.size.height = h;
        desLabel.frame = frame;
    }
    
    if (index == 0) {
        totalH = h;
    }else{
        totalH += h;
    }
    if (index == 2) {
        CGRect frame = self.personTableView.frame;
        frame.size.height = totalH;
        self.personTableView.frame = frame;
    }
    [cell addSubview:textLabel];
    [textLabel release];

    [desLabel release];
    
    return [cell autorelease];
}

- (UITableViewCell *)initCardTableViewCell:(NSInteger)index{
    UITableViewCell* cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    
    NSString* desStr = [self.cardDesArray objectAtIndex:index];
    
    UILabel* desLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, 100, 44)];
    desLabel.textColor = kNormalFontColor;
    desLabel.font = kNormalFont;
    desLabel.text = desStr;
    [cell addSubview:desLabel];
    
    UILabel* textLabel = [[UILabel alloc]initWithFrame:CGRectMake(110, 0, 200, 44)];
    textLabel.textColor = [UIColor blackColor];
    textLabel.font = kNormalFont;
    textLabel.textAlignment = NSTextAlignmentLeft;
    if (index == (self.cardDesArray.count - 1)) {
        NSString* cardNo = [self.confirmValueArray objectAtIndex:index + 3];
        if (!confirmFlag) {
            textLabel.text = [Utility encryptCardID:cardNo];
        }else{
            textLabel.text = [Utility getFormatCardID:cardNo];
        }
    }else{
        textLabel.text = [self.confirmValueArray objectAtIndex:index + 3];
    }
    NSUInteger h = [self heightWithLabel:textLabel];
    if (h > 44) {
        CGRect frame = desLabel.frame;
        frame.size.height = h;
        desLabel.frame = frame;
    }
    
    if (index == 0) {
        totalH = h;
    }else{
        totalH += h;
    }
    if (index == (self.cardDesArray.count - 1)) {
        CGRect frame = self.personTableView.frame;
        frame.size.height = totalH;
        self.cardTableView.frame = frame;
    }
    [cell addSubview:textLabel];
    [textLabel release];
    [desLabel release];
    
    return [cell autorelease];
}

- (UITableViewCell *)initDateTableViewCell{
    UITableViewCell* cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    
    UILabel* desLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 300, 44)];
    desLabel.textColor = kNormalFontColor;
    desLabel.font = kNormalFont;
    desLabel.text = ZZT_CLIENG.accountInfo.statusDescpriction;
    [cell addSubview:desLabel];
    [desLabel release];
    
    return [cell autorelease];
}

- (void)refreshUI{
    CGRect frame = self.personTableView.frame;
    
    CGRect titleFrame = self.cardTitleLabel.frame;
    titleFrame.origin.y = frame.origin.y + frame.size.height + 20;
    self.cardTitleLabel.frame = titleFrame;
    
    frame = self.cardTitleLabel.frame;
    CGRect cardFrame = self.cardTableView.frame;
    cardFrame.origin.y = frame.origin.y + frame.size.height + 5;
    self.cardTableView.frame = cardFrame;
    
    frame = self.nextButton.frame;
    frame.origin.y = cardFrame.origin.y + cardFrame.size.height + 15;
    
    if (confirmFlag) {
        self.nextButton.frame = frame;
    }
    
    frame = self.contentView.frame;
    if (!self.nextButton.hidden) {
        
        frame.size.height = self.nextButton.frame.origin.y + self.nextButton.frame.size.height + 15;
        
        self.scrollView.contentSize = CGSizeMake(ScreenWidth, self.nextButton.frame.origin.y + self.nextButton.frame.size.height + 10);
    }else{
        frame.size.height = cardFrame.origin.y + cardFrame.size.height + 15;
        self.scrollView.contentSize = CGSizeMake(ScreenWidth, cardFrame.origin.y + cardFrame.size.height + 10);
    }
    self.contentView.frame = frame;
    
    self.scrollView.contentSize = CGSizeMake(ScreenWidth, frame.size.height + frame.origin.y);
    
}
NSInteger totalH = 0;
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (([tableView isEqual:self.personTableView] && (indexPath.row != 1)) ||([tableView isEqual:self.cardTableView] && (indexPath.row == 1))) {
        NSString* str = nil;
        if ([tableView isEqual:self.personTableView]) {
            str = [self.confirmValueArray objectAtIndex:indexPath.row];
        }else{
            str = [self.confirmValueArray objectAtIndex:indexPath.row + 3];
        }
        UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(110, 0, 200, 44)];
        label.text = str;
        [label setFont:kNormalFont];
        
        NSUInteger h = [self heightWithLabel:label];
        [label release];
        
        return h;
    }
    
    return 44;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell* cell = nil;
    if ([tableView isEqual:self.personTableView]) {
        cell = [self initPersonTableViewCell:indexPath.row];
    }else if ([tableView isEqual:self.cardTableView]) {
        cell = [self initCardTableViewCell:indexPath.row];
    }else if ([tableView isEqual:self.dateTableView]){
        cell = [self initDateTableViewCell];
    }
    if ([tableView isEqual:self.dateTableView]) {
        if (indexPath.row == 0) {
            [self refreshUI];
        }
    }else if([tableView isEqual:self.cardTableView]){
        if (indexPath.row == (self.cardDesArray.count - 1)) {
            [self refreshUI];
        }
    }else{
        if (indexPath.row == 2) {
            [self refreshUI];
        }
    }
    
    
    return cell;
}

- (void)responseCallBackSuccess:(NSString *)action withData:(NSDictionary *)respData{
    if ([action isEqualToString:NET_ACTION_UPLOAD_PHOTO]){
        if (HPUIENG.progressView) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [HPUIENG.progressView updateProgress:nil];
            });
            
        }
        if (currentPhoto < kPhotoPlace) {
            currentPhoto++;
            [self uploadPhoto:NO];
        }else if (currentPhoto == kPhotoPlace){
            NSDictionary* photoDic = [self.screenData objectForKey:kPhotoKey];
            ZZTongPhotoButton* license = (ZZTongPhotoButton*)[photoDic objectForKey:@"license"];
            if (license) {
                if (!license.photoImageView.image) {
                    [self sendConfirmReq:@"1" personDic:[self.screenData objectForKey:@"person"] notUpPhoto:@"4"];
                }else{
                    currentPhoto++;
                    [self uploadPhoto:NO];
                }
            }
            
        }else if (currentPhoto == kPhotoLicense){
            [self sendConfirmReq:@"1" personDic:[self.screenData objectForKey:@"person"]];
        }
    }else if ([action isEqualToString:NET_ACTION_UPLOAD_UCINFO]){
        [HPUIENG removeWaiting];
        ZZT_CLIENG.accountInfo.accountStatus = AccountStatusReview;
        NSDictionary* personDic = [self.screenData objectForKey:@"person"];
        ZZT_CLIENG.accountInfo.shopName = [personDic objectForKey:@"shopName"];
        
        NSString * bindCSN = [[NSUserDefaults standardUserDefaults] objectForKey:BindCSN];
        if (bindCSN.length == 0)
        {
            bindCSN = @"";
        }
        NSString* str = [self.screenData objectForKey:KEY_SCREEN_NAME];
        if (str && [str isEqualToString:SCR_COLLECT_MONEY]) {
            NSDictionary* dic = @{KEY_SCREEN_NAME : str,BindCSN:bindCSN};
            [HPUIENG showScreen:SCR_UPLOAD_SUCCESS params:dic];
        }else{
            [HPUIENG showScreen:SCR_UPLOAD_SUCCESS params:@{BindCSN:bindCSN}];
        }
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:BindCSN];
    }
}

- (void)responseCallBackFailed:(NSString *)action withErrCode:(NSString *)errCode withErrMsg:(NSString *)msg{
    if ([action isEqualToString:NET_ACTION_UPLOAD_PHOTO]) {
        currentPhoto = -1;
    }
}

- (void)uploadPhoto:(BOOL)needShowWaiting{
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc]init];
    NSString* key = nil;
    switch (currentPhoto) {
        case kPhotoCertFront:
            key = @"certFront";
            break;
        case kPhotoCertBack:
            key = @"certBack";
            break;
        case kPhotoHead:
            key = @"head";
            break;
        case kPhotoPlace:
            key = @"place";
            break;
        case kPhotoLicense:
            key = @"license";
            break;
        default:
            break;
    }
    if (!key) {
        [pool release];
        return;
    }
    
	ZZTongClientEngine* zzt = ZZT_CLIENG;
    
    NSDictionary* photoDic = [self.screenData objectForKey:kPhotoKey];
    ZZTongPhotoButton* photo = (ZZTongPhotoButton*)[photoDic objectForKey:key];
    if (needShowWaiting) {
        NSUInteger stepNum = 5;
        NSDictionary* photoDic = [self.screenData objectForKey:kPhotoKey];
        ZZTongPhotoButton* license = (ZZTongPhotoButton*)[photoDic objectForKey:@"license"];
        if (license && license.photoImageView.image) {
            stepNum = 6;
        }
        [HPUIENG showProgress:@"正在提交资质材料..." steps:stepNum];
    }
    
    if (!photo.photoImageView.image) {
        [self responseCallBackSuccess:NET_ACTION_UPLOAD_PHOTO withData:nil];
        [pool release];
        return;
    }
    
    NSData* photoData = UIImageJPEGRepresentation(photo.photoImageView.image, 1);
    
    NSDictionary* params = @{KEY_PHONE: DES_ENC(zzt.accountInfo.mobile),
                             @"picType": [NSString stringWithFormat:@"%d", currentPhoto],
                             @"pic": photoData,
                             @"picCheck": [Utility crc32:photoData],
                             KEY_ACCOUNT: DES_ENC(ZZT_CLIENG.accountInfo.account),
                             KEY_CHANNEL: [zzt getChannel]};
    
    [zzt.netEngine sendRequest:NET_ACTION_UPLOAD_PHOTO withParams:params withDelegate:self withUploadImg:YES];
    
    
    [pool release];
}

- (void)sendConfirmReq:(NSString*)flag personDic:(NSDictionary*)personDic notUpPhoto:(NSString*)photoFlag{

    ZZTongClientEngine* zzt = ZZT_CLIENG;
    NSString * csn = [[NSUserDefaults standardUserDefaults] objectForKey:QualityCSN];
    
    NSDictionary* params = @{KEY_PHONE: DES_ENC(zzt.accountInfo.mobile),
                             @"name": DES_ENC([personDic objectForKey:@"name"]),
                             @"certNo": DES_ENC([personDic objectForKey:@"certNo"]),
                             @"shopName": DES_ENC([personDic objectForKey:@"shopName"]),
                             @"cardNum": DES_ENC([[personDic objectForKey:@"cardNo"] stringByReplacingOccurrencesOfString:@" " withString:@""]),
                             @"bankCode": [personDic objectForKey:@"bankCode"],
                             @"type": flag,
                             @"imageType": photoFlag,
                             KEY_NEWBANK_FLAG:@"1",
                             KEY_CHANNEL: [zzt getChannel],
                             KEY_LOCATION:[CSNValidator getLocation],
                             KEY_ADDRESS:[CSNValidator getAddress],
                             KEY_CSN : DES_ENC(csn),
                             };
    NSMutableDictionary* mutParams = [NSMutableDictionary dictionaryWithDictionary:params];
    NSString* subBankCode = [personDic objectForKey:@"subBankCode"];
    NSDictionary* provinceInfo = [personDic objectForKey:@"provinceInfo"];
    NSString* areaId = [personDic objectForKey:@"areaId"];
    if (subBankCode) {
        [mutParams setObject:subBankCode forKey:@"subBankCode"];
    }
    if (provinceInfo) {
        NSString* provinceId = [provinceInfo objectForKey:@"provinceId"];
        [mutParams setObject:provinceId forKey:@"provinceId"];
    }
    if (areaId) {
        [mutParams setObject:areaId forKey:@"areaId"];
    }

    
    LOG(@"params:%@", mutParams);
    [zzt.netEngine sendRequest:NET_ACTION_UPLOAD_UCINFO withParams:mutParams withDelegate:self];

    if (![flag isEqualToString:@"1"]) {
        [zzt.uiEngine showNetWaiting];
    }
}

- (void)sendConfirmReq:(NSString*)flag personDic:(NSDictionary*)personDic{
    [self sendConfirmReq:flag personDic:personDic notUpPhoto:@""];
}


- (IBAction)nextButtonClick:(id)sender {
    currentPhoto = kPhotoCertFront;
    [self uploadPhoto:YES];
}


@end
